<template>
  <div class="single-screen" v-if="screenVisible" :class="dialogClassName" @mouseenter="newDra" @click="selectDialog">
    <div class="screen-top">
      <div class="screen-top-title">
        <p>{{ screenDetail.info.brand_name }}</p>
        <p v-if="feimaManager">
          {{ feimaManager.fmMonitor.flightMission.province }}-{{ feimaManager.fmMonitor.flightMission.city }}-{{
            feimaManager.fmMonitor.flightMission.district
          }}
        </p>
      </div>
      <!-- 飞马 -->
      <div class="screen-top-msg" v-if="screenDetail.info.brand_name === '飞马'">
        <img :src="getPowerIcon()" alt="" />
        <p>{{ battery }}%</p>
        <img style="margin-left: 30px" src="@/assets/img/screen/icon_wifi.png" alt="" />
        <p style="margin-left: 30px; font-size: 16px">{{ '24' }}</p>
        <img style="margin-left: 10px" src="@/assets/img/screen/icon_gps.png" alt="" />
        <div class="screen-top-msg-gps" v-if="feimaManager">
          <p>PDOP:{{ feimaManager.fmMonitor.droneInfo.pdop }}</p>
          <p>GPS:{{ feimaManager.fmMonitor.droneInfo.gps_status }}</p>
        </div>
        <img
          style="width: 17px; height: 17px; margin-left: 44px; cursor: pointer"
          src="@/assets/img/home/icon_close.png"
          @click="closeScreenDialog"
          alt=""
        />
      </div>
      <!-- 其他 -->
      <div class="screen-top-msg" v-else>
        <img style="cursor: pointer" src="@/assets/img/screen/icon_tips.png" @click="clickTips" alt="" />
        <img
          style="width: 17px; height: 17px; margin-left: 39px; cursor: pointer"
          src="@/assets/img/home/icon_close.png"
          @click="closeScreenDialog"
          alt=""
        />
      </div>
    </div>
    <!-- 地图航线 -->
    <div class="single-screen-con" v-loading="loading">
      <div id="container" @click="onMapClick" :class="curContentType === 'video' ? 'map-small' : 'map-main'"></div>
      <!-- 右侧菜单 -->
      <div class="sildemenu" v-if="feimaManager && feimaManager.fmMonitor">
        <div class="sildemenu-item" @click="clickSildemenu(1)">
          <img v-show="sildemenuIndex1" src="@/assets/img/screen/icon_play_black.png" alt="" />
          <img v-show="!sildemenuIndex1" src="@/assets/img/screen/icon_play.png" alt="" />
        </div>

        <div class="sildemenu-item" @click="clickSildemenu(2)">
          <img v-show="sildemenuIndex2" src="@/assets/img/screen/icon_map_black.png" alt="" />
          <img v-show="!sildemenuIndex2" src="@/assets/img/screen/icon_map.png" alt="" />
        </div>
        <!-- 切换地图 -->
        <div class="map-postion" v-show="sildemenuIndex2">
          <div class="switch-map-con" @click="switchMap(1)" style="margin-right: 10px">
            <img v-show="mapIndex === 1" src="@/assets/img/home/icon_skymap_active.png" alt="" />
            <img v-show="mapIndex === 2" src="@/assets/img/home/icon_skymap.png" alt="" />
            <p :class="mapIndex === 1 ? 'active' : ''">天地图</p>
          </div>
          <div class="switch-map-con" @click="switchMap(2)">
            <img v-show="mapIndex === 2" src="@/assets/img/home/icon_map_active.png" alt="" />
            <img v-show="mapIndex === 1" src="@/assets/img/home/icon_map.png" alt="" />
            <p :class="mapIndex === 2 ? 'active' : ''">电子地图</p>
          </div>
        </div>
        <div class="sildemenu-item" @click="clickSildemenu(3)">
          <img v-show="sildemenuIndex3" src="@/assets/img/screen/icon_menu_black.png" alt="" />
          <img v-show="!sildemenuIndex3" src="@/assets/img/screen/icon_menu.png" alt="" />
        </div>
        <div class="menu-show" v-show="sildemenuIndex3">
          <div :class="isShowPanel ? 'selected' : 'unselected'" @click="showPanel">仪表盘</div>
          <div :class="isShowFlight ? 'selected' : 'unselected'" @click="showFlight()">航线</div>
          <div :class="isShowAirline ? 'selected' : 'unselected'" @click="showAirline()">轨迹</div>
        </div>
        <div class="sildemenu-item" @click="clickSildemenu(4)">
          <img v-show="sildemenuIndex4" src="@/assets/img/screen/icon_phone_black.png" alt="" />
          <img v-show="!sildemenuIndex4" src="@/assets/img/screen/icon_phone.png" alt="" />
        </div>
        <div class="phone-postion" v-show="sildemenuIndex4">
          <QrcodeVue :value="htmlUrl" :size="220" />
          <p>手机扫码观看</p>
        </div>
        <div class="sildemenu-item" @click="clickSildemenu(5)" v-if="!store.state.isOnline">
          <img v-show="sildemenuIndex5" src="@/assets/img/screen/icon_live_black.png" alt="" />
          <img v-show="!sildemenuIndex5" src="@/assets/img/screen/icon_live.png" alt="" />
        </div>
        <PlayBack
          v-if="sildemenuIndex5"
          @openBackPlay="openBackPlay"
          @moveProgress="moveProgress"
          @pause="pause"
          :packages="feimaManager.fmMonitor.flightMission.flight_log.packages"
        ></PlayBack>
      </div>
      <LiveVideo
        v-show="sildemenuIndex1"
        :isFull="curContentType === 'video'"
        :localId="screenDetail.info.mission_id"
        @clickContent="onVideoClick"
        @hideContent="hideContent"
      ></LiveVideo>
    </div>
    <!-- tips弹窗 -->
    <ul class="tips" v-show="tipsVisible">
      <li class="tips-item" v-for="(item, index) in tipsInfo" :key="index">
        <div class="tips-item-left">{{ item.label }}</div>
        <div class="tips-item-right">{{ screenDetail.info[item.key] }}</div>
      </li>
    </ul>
    <!-- 仪表盘 -->
    <div v-if="flightPanelDatas">
      <div class="flight-status" v-if="dashboardModel">
        <div class="flight-status-speed">
          <p class="flight-status-title">{{ flightPanelDatas.speed }}</p>
          <p class="flight-status-msg">
            飞行速度<span>目标{{ flightPanelDatas.target_speed.split('m')[0] }}</span>
          </p>
        </div>
        <div class="flight-status-height">
          <p class="flight-status-title">{{ flightPanelDatas.drone_height }}</p>
          <p class="flight-status-msg">
            飞行高度<span>目标{{ flightPanelDatas.target_height.split('m')[0] }}</span>
          </p>
        </div>
        <div class="flight-status-postion">
          <p class="flight-status-item">
            <span>纬度</span><span>{{ flightPanelDatas.latitude }}</span>
          </p>
          <p class="flight-status-item">
            <span>经度</span><span>{{ flightPanelDatas.longitude }}</span>
          </p>
          <p class="flight-status-item">
            <span>相对高度</span><span>{{ flightPanelDatas.drone_height }}</span>
          </p>
        </div>
        <div class="flight-status-time" v-if="flightPanelDatas">
          <p class="flight-status-item">
            <span>飞行时间</span><span>{{ flightPanelDatas.flight_duration }}</span>
          </p>
          <p class="flight-status-item">
            <span>更新时间</span><span>{{ flightPanelDatas.updated_at }}</span>
          </p>
          <p class="flight-status-item">
            <span>航迹角</span><span>{{ flightPanelDatas.angle }}</span>
          </p>
        </div>
        <div class="flight-status-line"></div>
        <div class="flight-status-distance" v-if="flightPanelDatas">
          <p class="flight-status-title">{{ flightPanelDatas.drone_pilot_distance }}</p>
          <p class="flight-status-msg">人机距离</p>
        </div>
        <!-- <div class="flight-status-temperature">
          <p class="flight-status-title">{{ flightPanelDatas.temperature }}</p>
          <p class="flight-status-msg">机身表面温度</p>
        </div> -->
        <div class="flight-status-mileage">
          <p class="flight-status-item">
            <span>航点</span><span>{{ flightPanelDatas.flight_progress }}</span>
          </p>
          <p class="flight-status-item">
            <span>里程</span><span>{{ flightPanelDatas.flight_miles }}</span>
          </p>
          <p class="flight-status-item">
            <span>照片</span><span>{{ flightPanelDatas.photo_count }}</span>
          </p>
        </div>
        <div class="flight-status-wind">
          <p class="flight-status-item">
            <span>风速</span><span>{{ flightPanelDatas.windSpeed }}</span>
          </p>
          <p class="flight-status-item">
            <span>地速</span><span>{{ flightPanelDatas.speed }}</span>
          </p>
        </div>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import {onMounted, Ref, ref, getCurrentInstance, nextTick, watch, toRaw} from 'vue';
import axios from 'axios';
import {useStore} from 'vuex';
import QrcodeVue from 'qrcode.vue';
import {FmMapManager, PathConfig} from '@/views/monitor/fmmapmanager';
import {imgPathConfig} from '@/views/monitor/monitorConfig';
import {wgs84togcj02} from '@/views/monitor/fmmapmanager/Tools/transfrom';
import LiveVideo from '@/components/liveVideo/LiveVideo.vue';
import PlayBack from '@/components/playBack/index.vue';
import SwitchMap from '@/utils/switchMap.js';
import UseDraggable from '@/utils/useDraggableElem';

const screenVisible = ref(false);
const tipsVisible = ref(false);
const screenDetail = ref();
const coordinate = ref('gcj02'); // 采用什么坐标系
const allPolyline = ref([]); // 地图上所有线集合，用于纠偏
const dashboardModel = ref(true);

// 侧边栏相关
const sildemenuIndex1 = ref(false);
const sildemenuIndex2 = ref(false);
const sildemenuIndex3 = ref(false);
const sildemenuIndex4 = ref(false);
const sildemenuIndex5 = ref(false);
const mapIndex = ref(2);
const isShowPanel = ref(true);
const isShowFlight = ref(true);
const isShowAirline = ref(true);
const htmlUrl = ref('');
const store = useStore();

const props = defineProps({
  screenVisible: Boolean,
  screenDetail: Object,
});

const emit = defineEmits(['closeScreen']);

type ListData = {
  label: string;
  key: string;
}[];

const tipsInfo: Ref<ListData> = ref([
  {label: '设备序列号', key: 'serial_no'},
  {label: '设备状态', key: 'device_status'},
  {label: '所属单位', key: 'unit_name'},
  {label: '联系人', key: 'contact_user'},
  {label: '联系人电话', key: 'contact_mobile'},
]);
// 关闭单屏监控弹窗
const closeScreenDialog = () => {
  emit('closeScreen');
  feimaManager.value.fmMonitor.initPlayback();
};
// 查看其他无人信息
const clickTips = () => {
  tipsVisible.value = !tipsVisible.value;
};

const $http = getCurrentInstance()?.appContext.config.globalProperties.$http;

let map: any;
let switchMapManage: any;
const loading = ref(false);
const isWgs = ref(false);
const feimaManager = ref();
let flyingAirline = ''; // 飞马无人机轨迹
let routeLine = ''; // 飞马航线
let feimaPlaneMarker = ''; // 飞马无人机图标标记点
let flyArea = []; // 阴影区域
const monitorDetail = ref();
const flightPanelDatas = ref();
const blockTypeList = [2, 3, 4, 8, 99];

// 关闭直播窗口
const hideContent = () => {
  sildemenuIndex1.value = !sildemenuIndex1.value;
};
// 播放回放
const openBackPlay = (allTime: Number) => {
  feimaManager.value.fmMonitor.openPlayBack(allTime);
};
// 暂停回放
const pause = () => {
  feimaManager.value.fmMonitor.pausePlayBack();
};
// 移动回放
const moveProgress = (precent = 0) => {
  feimaManager.value.fmMonitor
    .setPlaybackProgress(precent)
    .then(() => {
      if (flyingAirline === '') {
        this.flyingAirline = new AMap.Polyline({
          path: isWgs.value ? feimaManager.value.wgs84FlyingAirline.path : feimaManager.value.flyingAirline.path,
          strokeColor: feimaManager.value.wgs84FlyingAirline.strokeColor,
          strokeWeight: feimaManager.value.wgs84FlyingAirline.strokeWidth,
          zIndex: 50,
        });
        flyingAirline.setMap(this.map);
      } else if (isWgs.value) {
        flyingAirline.setPath(feimaManager.value.wgs84FlyingAirline.path);
      } else {
        flyingAirline.setPath(feimaManager.value.flyingAirline.path);
      }
    })
    .catch((err) => {
      throw err;
    });
};

// 显隐仪表盘
const showPanel = () => {
  dashboardModel.value = !dashboardModel.value;
  isShowPanel.value = !isShowPanel.value;
};
// 显隐航线
const showFlight = () => {
  isShowFlight.value = !isShowFlight.value;
  if (!routeLine) return;
  if (!isShowFlight.value) {
    // 隐藏航线
    routeLine.hide();
  } else {
    // 显示航线
    routeLine.show();
  }
};
// 显隐轨迹
const showAirline = () => {
  isShowAirline.value = !isShowAirline.value;
  if (!flyingAirline) return;
  if (!isShowAirline.value) {
    // 隐藏航线
    flyingAirline.hide();
  } else {
    // 显示航线
    flyingAirline.show();
  }
};
// 视频切换交互
// eslint-disable-next-line no-shadow
enum ContentType {
  map = 'map',
  video = 'video',
}
const curContentType = ref(ContentType.map);
const onMapClick = () => {
  // 隐藏窗口
  if (curContentType.value === 'video') {
    curContentType.value = ContentType.map;
  }
};

const onVideoClick = () => {
  if (curContentType.value === 'map') {
    curContentType.value = ContentType.video;
  }
};
// 电池图片
const getPowerIcon = () => {
  let range = Math.floor(parseInt(battery.value, 10) / 10) * 10;
  if (range <= 20) {
    range = 20;
  }
  // eslint-disable-next-line no-restricted-globals
  if (isNaN(range)) range = 100;
  return `/static/img/nav/battery_${range}.png`;
};
// 电量信息
const battery = ref(0);
const getBattery = (droneInfo) => {
  let count = 0;
  let sum = 0;
  for (const key in droneInfo) {
    if (
      Object.prototype.hasOwnProperty.call(droneInfo, key) &&
      key.includes('drone_battery_percent') &&
      droneInfo[key]
    ) {
      count++;
      if (!droneInfo[key].includes('undefined')) {
        sum += parseFloat(droneInfo[key]);
      }
    }
  }
  return sum / (count || 1);
};
// 选择侧边栏
const clickSildemenu = (index) => {
  switch (index) {
    case 1:
      sildemenuIndex1.value = !sildemenuIndex1.value;
      break;
    case 2:
      sildemenuIndex2.value = !sildemenuIndex2.value;
      break;
    case 3:
      sildemenuIndex3.value = !sildemenuIndex3.value;
      break;
    case 4:
      sildemenuIndex4.value = !sildemenuIndex4.value;
      break;
    case 5:
      sildemenuIndex5.value = !sildemenuIndex5.value;
      break;
    default:
      break;
  }
};
// 获取监控详情数据
const getMonitorDetail = async () => {
  const exportUrl = `${import.meta.env.VITE_MONITOR_URL}/flightMission/monitor`;
  const data = await axios({
    method: 'get',
    url: exportUrl,
    headers: {
      token: localStorage.getItem('token'),
    },
    params: {
      local_id: screenDetail.value.info.mission_id,
    },
  });

  if (!data.data.data.is_mission_flying) {
    const res = await axios({
      method: 'get',
      url: `${import.meta.env.VITE_MONITOR_URL}/flightLog/getDecode`,
      headers: {
        token: localStorage.getItem('token'),
      },
      params: {
        flight_mission_id: data.data.data.data.id,
      },
    });
    data.data.data.data.flight_log = {};
    data.data.data.data.flight_log.packages = res.data.data;
  }

  monitorDetail.value = data.data.data;
  init(monitorDetail.value);
};
// 初始化地图
const initMap = () => {
  loading.value = true;
  map = new AMap.Map('container', {
    resizeEnable: true,
    viewMode: '2D',
    zoom: 4,
    features: ['bg', 'road', 'building', 'point'],
  });
  switchMapManage = new SwitchMap(map);
  getMonitorDetail();
};
// 选择地图
const switchMap = (index) => {
  mapIndex.value = index;
  allPolyline.value = map.getAllOverlays('polyline');
  switchMapManage
    .switchDifferentMap(index)
    .then((res) => {
      if (res) {
        coordinate.value = 'wgs84';
        isWgs.value = true;
        switchSkyMap();
      } else {
        coordinate.value = 'gcj02';
        isWgs.value = false;
        switchGaoDe();
      }
    })
    .catch((err) => {
      throw err;
    });
};
// 切换成天地图时
const switchSkyMap = () => {
  routeLine.setMap(null);
  flyArea.setMap(null);
  homePoint.setMap(null);
  endPoint.setMap(null);
  if (flyingAirline) {
    flyingAirline.setMap(null);
  }
  routeLine = new AMap.Polyline({
    ...feimaManager.value.wgs84Airline,
    zIndex: 50,
  });
  flyArea = new AMap.Polygon({
    path: getFlyArea(monitorDetail.value.data),
    fillColor: '#fdfbb1', // 多边形填充颜色
    borderWeight: 2, // 线条宽度，默认为 1
    strokeColor: '#e8a443', // 线条颜色
    zIndex: 30,
  });
  // 判断是否是条带航线
  if (blockTypeList.includes(store.state.blockType)) {
    flyArea = new AMap.Polyline({
      path: getFlyArea(monitorDetail.value.data),
      strokeColor: store.state.isOnline ? '#e8a443' : '#24DBFF',
      strokeOpacity: 1,
      strokeWeight: 6,
      // 折线样式还支持 'dashed'
      strokeStyle: 'solid',
      // strokeStyle是dashed时有效
      strokeDasharray: [10, 5],
      lineJoin: 'round',
      lineCap: 'round',
      zIndex: 30,
    });
  } else {
    flyArea = new AMap.Polygon({
      path: getFlyArea(monitorDetail.value.data),
      fillColor: store.state.isOnline ? '#CCC894' : '#95BDCA', // 多边形填充颜色
      borderWeight: 2, // 线条宽度，默认为 1
      strokeColor: store.state.isOnline ? '#e8a443' : '#24DBFF', // 线条颜色
      zIndex: 30,
    });
  }
  flyingAirline = new AMap.Polyline({
    path: [],
    strokeColor: feimaManager.value.wgs84FlyingAirline.strokeColor,
    strokeWeight: feimaManager.value.wgs84FlyingAirline.strokeWidth,
    zIndex: 50,
  });
  flyingAirline.setMap(map);
  map.add(flyArea);
  routeLine.setMap(map);
  map.setFitView(routeLine);
  homePointMarker(feimaManager.value.wgs84Markers[0]);
  endPointMarker(feimaManager.value.wgs84Markers[1]);
};
// 切换到电子地图
const switchGaoDe = () => {
  routeLine.setMap(null);
  flyArea.setMap(null);
  homePoint.setMap(null);
  endPoint.setMap(null);
  if (flyingAirline) {
    flyingAirline.setMap(null);
  }
  routeLine = new AMap.Polyline({
    ...feimaManager.value.airline,
    zIndex: 50,
  });
  // 判断是否是条带航线
  if (blockTypeList.includes(store.state.blockType)) {
    flyArea = new AMap.Polyline({
      path: getFlyArea(monitorDetail.value.data),
      strokeColor: store.state.isOnline ? '#e8a443' : '#24DBFF',
      strokeOpacity: 1,
      strokeWeight: 6,
      // 折线样式还支持 'dashed'
      strokeStyle: 'solid',
      // strokeStyle是dashed时有效
      strokeDasharray: [10, 5],
      lineJoin: 'round',
      lineCap: 'round',
      zIndex: 30,
    });
  } else {
    flyArea = new AMap.Polygon({
      path: getFlyArea(monitorDetail.value.data),
      fillColor: store.state.isOnline ? '#CCC894' : '#95BDCA', // 多边形填充颜色
      borderWeight: 2, // 线条宽度，默认为 1
      strokeColor: store.state.isOnline ? '#e8a443' : '#24DBFF', // 线条颜色
      zIndex: 30,
    });
  }
  flyingAirline = new AMap.Polyline({
    path: [],
    strokeColor: feimaManager.value.flyingAirline.strokeColor,
    strokeWeight: feimaManager.value.flyingAirline.strokeWidth,
    zIndex: 50,
  });
  flyingAirline.setMap(map);
  map.add(flyArea);
  routeLine.setMap(map);
  map.setFitView(routeLine);
  homePointMarker(feimaManager.value.markers[0]);
  endPointMarker(feimaManager.value.markers[1]);
};

// 设置起飞点和结束点标记点
let homePoint;
const homePointMarker = (makerData) => {
  homePoint = new AMap.Marker({
    position: makerData.lnglat,
    icon: makerData.icon,
    zIndex: 111,
    offset: new AMap.Pixel(0, 0),
    anchor: 'center',
  });
  map.add(homePoint);
};
let endPoint;
const endPointMarker = (makerData) => {
  endPoint = new AMap.Marker({
    position: makerData.lnglat,
    icon: makerData.icon,
    zIndex: 111,
    offset: new AMap.Pixel(0, 0),
    anchor: 'center',
  });

  map.add(endPoint);
};
// 设置飞马无人机图标标记点，因为要多次赋值经纬度，所以要绑定数据
const setFeimaPlaneMarker = (data) => {
  feimaPlaneMarker = new AMap.Marker({
    position: data.lnglat,
    icon: data.icon,
    zIndex: 111,
    offset: new AMap.Pixel(0, 0),
    anchor: 'center',
  });
  map.add(feimaPlaneMarker);
};
// 获取websocket Url
const getPlaneWebsocketUrl = () =>
  new Promise((resolve, reject) => {
    $http
      .get('//airport.afuav.com/api/device/monitor/info', {
        serial_no: screenDetail.value.info.serial_no,
      })
      .then((response) => {
        resolve(response.data);
      })
      .catch((error) => {
        reject(error);
      });
  });
// 获取阴影区域数据
const getFlyArea = (areaData) => {
  const areaArr = [];
  let posi = [];
  areaData.survey_area_coordinate_points.split(';').forEach((item) => {
    if (item) {
      const [lat, lng] = item.split(',');
      posi = wgs84togcj02(lng, lat);
      if (isWgs.value) {
        areaArr.push([lng, lat]);
      } else if (areaData.plane_type === 'Phantom 4 Pro') {
        areaArr.push([lng, lat]);
      } else {
        areaArr.push([posi.longitude, posi.latitude]);
      }
    }
  });
  return areaArr;
};
// 初始化飞行数据
const init = async (data) => {
  let wsUrl = '';
  let tbId = '';
  await getPlaneWebsocketUrl().then((res) => {
    wsUrl = res.ws_url;
    tbId = res.data.tb_id;
  });
  const fmMonitorOptions = {
    flight_data: data.data, // 必填。 请求到的任务数据
    local_id: data.data.local_id, // 必填。任务id
    url: wsUrl, // 必填。websocket监听地址
    platform: '', // 选填。不填默认web端
    isWgsNeeded: false, // 选填。不填默认false， 即 不生成wgs航线/标记点
    /*
     * airlineOptions 航线配置
     * base_airline_options: 底层航线，upper_airline_options： 上层航线
     * 具体航线配置参考Polyline文档
     */
    airlineOptions: {
      base_airline_options: {
        // 选填。底层航线
        strokeColor: '#e8a443',
        strokeWidth: 2,
        id: '1',
      },
      upper_airline_options: {
        // 选填。上层航线
        strokeColor: '#1686cc',
        strokeWidth: 2,
        id: '2',
      },
    },
    /*
     * markersOptions 标记点配置
     * landingMarker: 起飞点，endPointMarker: 终止点，planeMarker:飞机；
     * 网页端参考amap marker文档, uniapp端参考文档。配置除图片和位置外的所需参数
     */
    markersOptions: {
      landingMarker: {}, // 起飞点
      endPointMarker: {}, // 终止点
      planeMarker: {}, // 飞机
    },
  };

  fmMonitorOptions.wsMessageFunc = () =>
    `{"attrSubCmds":[],"tsSubCmds":[{"entityType":"DEVICE","entityId":"${tbId}","scope":"LATEST_TELEMETRY","cmdId":1}],"historyCmds":[]}`;
  PathConfig.setConfigs(imgPathConfig); // 图片路径
  feimaManager.value = new FmMapManager(fmMonitorOptions);
  feimaManager.value.createMonitor();
  feimaManager.value.onPlaneMove = (item) => {
    getFeimaWebsocketData(item);
  };
  htmlUrl.value =
    import.meta.env.VITE_MONITOR_URL + '/?local_id=' + feimaManager.value.fmMonitor.flightMission.local_id;

  // 判断是否是条带航线
  if (blockTypeList.includes(store.state.blockType)) {
    flyArea = new AMap.Polyline({
      path: getFlyArea(data.data),
      strokeColor: store.state.isOnline ? '#e8a443' : '#24DBFF',
      strokeOpacity: 1,
      strokeWeight: 6,
      // 折线样式还支持 'dashed'
      strokeStyle: 'solid',
      // strokeStyle是dashed时有效
      strokeDasharray: [10, 5],
      lineJoin: 'round',
      lineCap: 'round',
      zIndex: 30,
    });
  } else {
    flyArea = new AMap.Polygon({
      path: getFlyArea(data.data),
      fillColor: store.state.isOnline ? '#CCC894' : '#95BDCA', // 多边形填充颜色
      borderWeight: 2, // 线条宽度，默认为 1
      strokeColor: store.state.isOnline ? '#e8a443' : '#24DBFF', // 线条颜色
      zIndex: 30,
    });
  }
  if (isWgs.value) {
    routeLine = new AMap.Polyline({
      ...feimaManager.value.wgs84Airline,
      zIndex: 50,
    });
    map.add(flyArea);
    routeLine.setMap(map);
    map.setFitView(routeLine);
    homePointMarker(feimaManager.value.wgs84Markers[0]);
    endPointMarker(feimaManager.value.wgs84Markers[1]);
  } else {
    routeLine = new AMap.Polyline({
      ...feimaManager.value.airline,
      zIndex: 50,
    });

    map.add(flyArea);
    routeLine.setMap(map);
    map.setFitView(routeLine);
    homePointMarker(feimaManager.value.markers[0]);
    endPointMarker(feimaManager.value.markers[1]);
  }
  // 设置飞机
  // websocket端口
  feimaManager.value.errorMonitor = (error) => {
    this.$message('连接已断开，请重新进入');
  };
  feimaManager.value.fmMonitor.onDroneInfoUpdated = () => {
    battery.value = getBattery(feimaManager.value.fmMonitor.droneInfo);
  };
  feimaManager.value.fmMonitor.onFlightPanelDatasUpdated = () => {
    flightPanelDatas.value = feimaManager.value.fmMonitor.flightPanelDatas;
  };
  loading.value = false;
  if (!store.state.isOnline) {
    openBackPlay();
  }
};
// 飞马标记点移动时的数据
const getFeimaWebsocketData = (data) => {
  if (flyingAirline === '') {
    flyingAirline = new AMap.Polyline({
      path: [],
      strokeColor: feimaManager.value.wgs84FlyingAirline.strokeColor,
      strokeWeight: feimaManager.value.wgs84FlyingAirline.strokeWidth,
      zIndex: 50,
    });
    flyingAirline.setMap(map);
  } else {
    const path = flyingAirline.getPath();
    if (isWgs.value) {
      path.push([
        feimaManager.value.fmMonitor.wgs84CurrentPosition.longitude,
        feimaManager.value.fmMonitor.wgs84CurrentPosition.latitude,
      ]);
      flyingAirline.setPath(path);
    } else {
      path.push([
        feimaManager.value.fmMonitor.currentPosition.longitude,
        feimaManager.value.fmMonitor.currentPosition.latitude,
      ]);
      flyingAirline.setPath(path);
    }
  }
  if (feimaPlaneMarker === '') {
    if (feimaManager.value.markers[2] !== undefined) {
      const planeMarker = feimaManager.value.markers[2];
      setFeimaPlaneMarker(planeMarker);
    }
  } else {
    if (isWgs.value) {
      feimaPlaneMarker.setPosition([
        feimaManager.value.fmMonitor.wgs84CurrentPosition.longitude,
        feimaManager.value.fmMonitor.wgs84CurrentPosition.latitude,
      ]);
    } else {
      feimaPlaneMarker.setPosition([
        feimaManager.value.fmMonitor.currentPosition.longitude,
        feimaManager.value.fmMonitor.currentPosition.latitude,
      ]);
    }
    feimaPlaneMarker && feimaPlaneMarker.setAngle(feimaManager.value.fmMonitor.planeRotate);
  }
};
// 拖拽相关
const dialogClassName = ref('dialogClassName');
let draggable;

const setUseDraggable = () => {
  dialogClassName.value += store.state.dialogClassNameCount;
  store.commit('changeDialogClassNameCount', 1);
  const params = {
    fatherSelector: dialogClassName.value,
  };
  nextTick(() => {
    draggable = new UseDraggable(params);
    const sonDom = document.getElementsByClassName(dialogClassName.value)[0];
    sonDom.parentNode.style.zIndex = store.state.dialogzIndex;
  });
};

watch(
  () => screenVisible.value,
  (newVal) => {
    if (newVal && draggable !== '') {
      // 元素拖拽
      draggable = setUseDraggable();
    }
  },
);
const newDra = () => {
  const params = {
    fatherSelector: dialogClassName.value,
  };
  // eslint-disable-next-line no-new
  new UseDraggable(params);
};
const selectDialog = () => {
  try {
    const sonDom = document.getElementsByClassName(dialogClassName.value)[0];
    sonDom.parentNode.style.zIndex = store.state.dialogzIndex;
    store.commit('changeDialogzIndex', 1);
  } catch {}
};
onMounted(() => {
  screenVisible.value = props.screenVisible;
  screenDetail.value = props.screenDetail;
  setTimeout(() => {
    initMap();
  }, 10);
});
</script>
<style lang="scss" scoped>
@import './SingScreen.scss';
</style>
